import React from 'react';
import {useDispatch} from "react-redux";

/**
 * redux部分源码
 * @returns {Element}
 * @constructor
 */
export const ReduxCodeComp = function () {
    return (
        <>

        </>
    )

};



export const createStore = (func)=>{
    //返回的state
    let stateInstance = null;
    let initValue = null;
    //事件池
    let listenerList =[];
    if (typeof func !== 'function') {
        throw new TypeError('Expected a function');
    }

    const getState = ()=>{
        return stateInstance;
    }

    const subscribe  = (listener)=>{
        if(!listenerList.includes(listener)){
            listenerList.push(listener);
        }
        return function deleteListener(listener){
            listenerList.splice(listenerList.indexOf(listener),1);
        }
    }

    //派发行为
    const dispatch = (action)=>{
        if (action.type === undefined){
            throw new Error('Action is required');
        }
        //执行
        func(stateInstance, action);
        //状态更改的话还需要把事件池中的事件执行
        listenerList.forEach(listener=>{
            listener();
        })

        return action;
    }

    //redux内部会默认进行一次dispatch派发,目的是给容器中的公共状态赋初始值
    dispatch({
        type:Math.random().toString(33).substring(6,10)
    })



    return {
        subscribe,getState,dispatch
    }

}